import uix
import form
import xtriui
import os
import uiconst
import blue
import bluepy
import uiutil
import uthread
import uiutil
import util
import inspect
import uicls

class WindowManager(uicls.Window):
    __guid__ = 'form.WindowManager'

    def ApplyAttributes(self, attributes):
        uicls.Window.ApplyAttributes(self, attributes)
        self.SetWndIcon(None)
        self.SetCaption('Window manager')
        self.SetTopparentHeight(10)
        self.SetMinSize([360, 220])
        options = []
        windowList = list(form.__all_form__)
        windowList.sort()
        for (i, f,) in enumerate(windowList):
            cp = form.__getattribute__(f)
            if (inspect.isclass(cp) and issubclass(cp, uicls.Window)):
                options.append((f, i))

        topCont = uicls.Container(name='params', parent=self.sr.main, align=uiconst.TOTOP, pad=(5, 5, 5, 5), pos=(0, 10, 0, 30))
        self.mainCont = uicls.Container(name='params', parent=self.sr.main, align=uiconst.TOTOP, pos=(0, 0, 0, 50), padding=(5, 15, 5, 5))
        self.extrasCont = uicls.Container(name='params', parent=self.sr.main, align=uiconst.TOALL, padding=(5, 15, 5, 5))
        self.combo = uicls.Combo(parent=topCont, label='Select window', options=options, name='', select=settings.user.ui.Get('windowManagerOpenWindow'), callback=self.OnComboChanged, pos=(5, 0, 0, 0), width=150, align=uiconst.TOPLEFT)
        self.startupArgs = uicls.SinglelineEdit(name='', label='attributes', parent=topCont, setvalue='', align=uiconst.TOPLEFT, left=165, width=100)
        uicls.Button(parent=topCont, label='Load', align=uiconst.UI_ALNONE, func=self.OpenWindow, pos=(300, 0, 0, 0))
        self.filenameEdit = uicls.SinglelineEdit(name='', label='Location', parent=self.mainCont, setvalue='', align=uiconst.TOTOP, top=15, readonly=True)
        uicls.Label(text='RELOAD', parent=self.extrasCont, top=10, state=uiconst.UI_NORMAL)
        uicls.Line(parent=self.extrasCont, align=uiconst.TOTOP)
        buttonCont = uicls.Container(name='buttonCont', parent=self.extrasCont, align=uiconst.TOTOP, pos=(0, 30, 0, 30))
        uicls.Button(parent=buttonCont, label='ShipUI', align=uiconst.TOLEFT, func=self.ReloadShipUI)
        uicls.Button(parent=buttonCont, label='NEOCOM', align=uiconst.TOLEFT, func=self.ReloadNeocom)
        uicls.Button(parent=buttonCont, label='Lobby', align=uiconst.TOLEFT, func=self.ReloadLobby)
        uicls.Button(parent=buttonCont, label='Overview', align=uiconst.TOLEFT, func=self.ReloadOverview)
        self.UpdateInfo(self.combo.GetKey(), self.combo.GetValue())



    def OnComboChanged(self, combo, key, index):
        self.UpdateInfo(key, index)



    def UpdateInfo(self, key, index):
        window = form.__getattribute__(key)
        self.filenameEdit.SetValue(window.ApplyAttributes.func_code.co_filename)
        settings.user.ui.Set('windowManagerOpenWindow', index)



    def OpenWindow(self, *args):
        windowName = self.combo.GetKey()
        w = sm.GetService('window').GetWindow(windowName)
        if w:
            w.SelfDestruct()
        attributes = {}
        try:
            attributesStr = self.startupArgs.GetValue()
            if attributesStr:
                for s in attributesStr.split(','):
                    (keyword, value,) = s.split('=')
                    keyword = keyword.strip()
                    value = value.strip()
                    try:
                        if (value.find('.') != -1):
                            value = float(value)
                        else:
                            value = int(value)
                    except ValueError:
                        pass
                    if (value == 'None'):
                        value = None
                    attributes[keyword] = value

        except:
            eve.Message('CustomInfo', {'info': 'attributes must be on the form: attr1=1, attr2=Some random text'})
            raise 
        sm.GetService('window').GetWindow(windowName, create=1, **attributes)



    def ReloadShipUI(self, *args):
        if (eve.session.stationid is None):
            uicore.layer.shipui.CloseView()
            uicore.layer.shipui.OpenView()



    def ReloadNeocom(self, *args):
        svcName = 'neocom'
        sm.StopService(svcName)
        sm.StartService(svcName)



    def ReloadLobby(self, *args):
        if session.stationid:
            sm.GetService('station').GetLobby(create=True, doReload=True)



    def ReloadOverview(self, *args):
        wnd = sm.GetService('window').GetWindow('overview', decoClass=form.OverView)
        if wnd:
            wnd.SelfDestruct()
        if session.solarsystemid:
            sm.GetService('tactical').InitOverview()
        wnd = sm.GetService('window').GetWindow('selecteditemview', decoClass=form.ActiveItem)
        if wnd:
            wnd.SelfDestruct()
        if session.solarsystemid:
            sm.GetService('tactical').InitSelectedItem()
        wnd = sm.GetService('window').GetWindow('droneview', decoClass=form.DroneView)
        if wnd:
            wnd.SelfDestruct()
        if session.solarsystemid:
            sm.GetService('tactical').InitDrones()




